package com.zbkj.crmeb.supplier.controller;

import java.util.Arrays;
import java.util.Map;

// import org.apache.shiro.authz.annotation.RequiresPermissions;
import com.alibaba.fastjson.JSONObject;
import com.zbkj.crmeb.front.request.ProductRequest;
import com.zbkj.crmeb.front.response.ProductResponse;
import com.zbkj.crmeb.merchant.api.controller.ApiBaseController;
import com.zbkj.crmeb.supplier.service.SupplierOpenShopService;
import com.zbkj.crmeb.user.model.User;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.PageInfo;
import com.zbkj.crmeb.chant.dto.ApplyAuditAndSupplierDTO;
import com.zbkj.crmeb.chant.dto.ChannelMerchantSupplierDTO;
import com.zbkj.crmeb.chant.model.ChannelActivity;
import com.zbkj.crmeb.member.model.ChannelMerchantAttribute;
import com.zbkj.crmeb.store.request.BusinessApplyRequest;
import com.zbkj.crmeb.store.request.CustomsRecordSearchRequest;
import com.zbkj.crmeb.store.response.BusinessApplyResponse;
import com.zbkj.crmeb.supplier.model.BusinessApply;
import com.zbkj.crmeb.supplier.service.BusinessApplyService;
import com.zbkj.crmeb.user.service.UserService;

import javax.servlet.http.HttpServletRequest;


/**
 * 某业务的注册申请表
 *
 * @author lss
 * @email didiok@foxmail.com
 * @date 2024-11-18 17:36:49
 */
@Slf4j
@RestController
@RequestMapping("api/admin/supplier/business/apply")
public class BusinessApplyController extends ApiBaseController {
    @Autowired
    private BusinessApplyService businessApplyService;

    @Autowired
    private UserService userService;

    /**
     * 分页显示注册申请
     *
     * @param request          搜索条件
     * @param pageParamRequest 分页参数
     */
    @ApiOperation(value = "注册申请分页列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public CommonResult<CommonPage<BusinessApplyResponse>> getList(@Validated BusinessApplyRequest request, @Validated PageParamRequest pageParamRequest) {
        PageInfo<BusinessApplyResponse> pageInfo = new PageInfo<>();
        try {
            pageInfo = businessApplyService.getList(request, pageParamRequest);
        }catch (Exception e){
            log.error("注册申请分页列表查询报错，", e);
            throw new CrmebException("注册申请分页列表查询报错");
        }
        return CommonResult.success(CommonPage.restPage(pageInfo));
    }

    /**
     * 添加供应商
     */
    @ApiOperation(value = "酒庄审核并添加供应商")
    @RequestMapping(value = "/audit", method = RequestMethod.POST)
    public CommonResult<String> businessApplyAudit(@RequestBody ApplyAuditAndSupplierDTO entity){
        try {
            return businessApplyService.businessApplyAudit(entity);
        }catch (Exception e){
            log.error("酒庄审核并添加供应商报错，", e);
            throw new CrmebException("酒庄审核并添加供应商报错");
        }
    }

    /**
     * 查询酒庄注册信息
     * @param id Integer
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "详情")
    @GetMapping("/info/{id}")
    public CommonResult<BusinessApply> info(@PathVariable Integer id) {
        BusinessApply businessApply = new BusinessApply();
        try{
            businessApply = businessApplyService.getById(id);
        }catch (Exception e){
            log.error("查询酒庄注册信息报错，", e);
            throw new CrmebException("查询酒庄注册信息报错");
        }
        return CommonResult.success(businessApply);
    }

    /**
     * 查询酒庄注册信息
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "详情")
    @GetMapping("/detail")
    public CommonResult<BusinessApply> detail() {
        Integer userId = userService.getUserIdException();
        BusinessApply businessApply = new BusinessApply();
        try{
            businessApply = businessApplyService.getOne(Wrappers.<BusinessApply>lambdaQuery()
                    .eq(BusinessApply::getCreateUserUid, userId)
                    .last("LIMIT 1"));
        }catch (Exception e){
            log.error("查询酒庄注册信息报错，", e);
            throw new CrmebException("查询酒庄注册信息报错");
        }
        return CommonResult.success(businessApply);
    }

    /**
     * 新增注册申请
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "新增")
    @PostMapping("/save")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> save(@RequestBody @Validated BusinessApply businessApply, HttpServletRequest request) {

        int isHas = businessApplyService.count(Wrappers.<BusinessApply>lambdaQuery()
                .eq(BusinessApply :: getTitle, businessApply.getTitle())
                .eq(BusinessApply :: getBusinessCode, businessApply.getBusinessCode())
        );
        if(isHas > 0) {
            return CommonResult.failed("注册申请的名称已存在！");
        }
        boolean b = false;
        try{
            businessApply.setMerId(getMerId(request));
            User userInfo = userService.getInfoException();
            businessApply.setCreateUserUid(userInfo.getUid());
            businessApply.setCreateUserName(userInfo.getRealName());
            businessApply.setAuditStatus(1); //待审核
            b = businessApplyService.save(businessApply);
        }catch (Exception e){
            log.error("酒庄注册申请报错，", e);
            throw new CrmebException("酒庄注册申请报错");
        }

        // 处理富文本
        return b ? CommonResult.success() : CommonResult.failed();
    }

    /**
     * 修改注册申请
     * @param businessApply 修改参数
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "修改")
    @PutMapping("/update")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> update(@RequestBody @Validated BusinessApply businessApply) {
        int count = businessApplyService.count(Wrappers.<BusinessApply>lambdaQuery()
                .eq(BusinessApply :: getTitle, businessApply.getTitle())
                .eq(BusinessApply :: getBusinessCode, businessApply.getBusinessCode())
                .ne(BusinessApply::getId, businessApply.getId())
        );
        if(count > 0){
            return CommonResult.failed("注册申请的名称已存在");
        }
        boolean b = false;
        try{
            b = businessApplyService.updateById(businessApply);
        }catch (Exception e){
            log.error("酒庄修改注册申请报错，", e);
            throw new CrmebException("酒庄修改注册申请报错");
        }

        return b ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "删除")
    @DeleteMapping("/delete/{id}")
    public CommonResult<String> delete(@PathVariable Integer id) {
        boolean b = false;
        try{
            b = businessApplyService.removeById(id);
        }catch (Exception e){
            log.error("酒庄修改注册申请报错，", e);
            throw new CrmebException("酒庄修改注册申请报错");
        }

        return b ? CommonResult.success() : CommonResult.failed();
    }

}
